# e9cdf437c2c84b088c18008d6d225172
# http://swagger.emby.media/?staticview=true#/MoviesService
import base64
import json
from pprint import pprint
from urllib.parse import quote

import requests
from pymediainfo import MediaInfo
# 控制面板-》高级-》api密钥
from unipath import Path, FILES

api_key = 'ac09e924c9f443fd95b6300ab4ab4ac0'
domain = 'http://localhost:8096'
image_root_path = ''


# ----------------------------------------- 工具


# 获取文件的base64编码字符串
def get_base64_str(file_path):
    """
        获取文件的base64编码字符串
    :param file_path: 文件路径
    :return: base64编码
    """
    return base64.b64encode(open(file_path, 'rb').read())


# 获取演员的ID
def get_actorer_id(actor_name: str):
    """
        获取演员的信息
    :param actor_name:  演员的信息，查询失败，返回500错误
    :return: json
    """
    url = '{0}/emby/Persons/{1}'.format(domain, quote(actor_name, 'utf-8'))
    headers = {
        'accept': 'application/json'
    }
    # 参数
    params = {'api_key': api_key}
    # 请求数据
    response = requests.get(headers=headers, url=url, params=params)

    # 查询失败
    if response.status_code != 200:
        return None

    return response.json()


def get_actor_pic_path(actor_name: str):
    pass


# ----------------------------------------- 更新演员头像


# 更新演员头像
def update_actorer_pic(actor_id, image_path):
    # 地址
    url = '{0}/emby/Items/{1}/Images/Primary'.format(domain, str(actor_id))
    # 参数
    params = {'api_key': api_key}

    # 请求头信息
    headers = {
        'Content-Type': 'image/jpeg'
    }
    # 上传文件，返回结果
    response = requests.post(headers=headers, url=url, data=get_base64_str(image_path), params=params)
    return response.text


# 更新一个演员的头像
def update_actorer_pic_one(artorer_name: str):
    # 获取演员ID

    pass


# 更新多个演员信息
def update_actorer_pic_many(artorer_name: list):
    pass


# 更新所有演员的头像
def update_actorer_pic_all():
    # 地址
    url = '{0}/emby/Persons'.format(domain)
    # 参数
    params = {'api_key': api_key}

    no_person_pic_list = []
    # 请求头信息
    headers = {
        'Content-Type': 'image/jpeg'
    }
    response = requests.get(headers=headers, url=url, params=params)
    actors = dict(response.json())['Items']
    count = 0
    count_all = str(len(actors))
    print('[+] 找到' + count_all + ' 演员')

    # 头像名称和路径的映射
    actorer_dir = []
    print('[+] 加载所有头像')
    for item in Path(image_root_path).walk(filter=FILES):
        actorer_dir.append(item)
    # 上传文件，返回结果
    for item in actors:
        count = count + 1
        percentage = str(count / int(count_all) * 100)[:4] + '%'
        if len(item['ImageTags']) > 0:
            print('[#] - ' + percentage + ' [' + str(count) + '/' + count_all + '] - ' + item['Name'])
            continue
        actor_id = item['Id']

        current_actorer_path = None
        # 如果文件不存在，就跳过
        for temp_item in actorer_dir:
            if str(temp_item.stem) == str(item['Name']):
                current_actorer_path = temp_item
                break
        if not current_actorer_path:
            print('[!] - ' + percentage + ' [' + str(count) + '/' + count_all + '] - ' + item['Name'])
            continue
        # 更新
        response_update = update_actorer_pic(actor_id, current_actorer_path)
        print(response_update)
        print('[+] - ' + percentage + ' [' + str(count) + '/' + count_all + '] - ' + item['Name'])

    [print('[#] {0}'.format(item)) for item in no_person_pic_list]


# 更新av头像信息
def update_actorer_pic_jav(pic_root_path):
    pic_root_path = Path(pic_root_path)
    if not pic_root_path.exists():
        print("[!] 文件夹不存在 {0}".format(pic_root_path))
        return
    # 地址
    url = '{0}/emby/Persons'.format(domain)
    # 参数
    params = {'api_key': api_key}

    no_person_pic_list = []
    # 请求头信息
    headers = {
        'Content-Type': 'image/jpeg'
    }
    response = requests.get(headers=headers, url=url, params=params)
    actors = dict(response.json())['Items']
    if len(actors) == 0:
        print("[!] {0}".format("没有找到头像信息"))
        return
    actor_map = {}
    # 加载头像信息
    for item_file_path in pic_root_path.walk(filter=FILES):
        if item_file_path.stem in actor_map.keys():
            continue
        print("[+] {0}".format(item_file_path))
        actor_map[str(item_file_path.stem)] = item_file_path

    count = 0
    count_all = str(len(actors))
    print('[+] 找到' + count_all + ' 演员')

    # 上传文件，返回结果
    for item in actors:
        count = count + 1
        percentage = str(count / int(count_all) * 100)[:4] + '%'
        print('[+] - ' + percentage + ' [' + str(count) + '/' + count_all + '] - ' + item['Name'])
        if len(item['ImageTags']) > 0:
            continue
        actor_id = item['Id']

        # 不存在就跳过
        pic_file_path = actor_map.get(item['Name'])
        if not pic_file_path:
            continue
        if not pic_file_path.exists():
            no_person_pic_list.append(item['Name'])
            continue
        response_update = update_actorer_pic(actor_id, pic_file_path)
        print(response_update)

    [print('[#] {0}'.format(item)) for item in no_person_pic_list]


# ----------------------------------------- 更新演员头像

# 获取所有的演员
def get_all_actorer():
    """
        1、获取所有的演员
    :return: json数据
    """
    url = '{0}/emby/Persons'.format(domain)
    headers = {
        'accept': 'application/json'
    }
    params = {'api_key': api_key}
    response = requests.get(headers=headers, url=url, params=params)
    return response.json()


def get_simple_users(person_info):
    headers = {
        'accept': 'application/json'
    }
    # / 206
    # params = {“wd”: “股票”}
    response = requests.get(headers=headers,
                            url='http://localhost:8096/emby/Persons/' + quote(person_info, 'utf-8') + '?api_key=e9cdf437c2c84b088c18008d6d225172')
    print(json.dumps(response.json(), sort_keys=True, indent=4, separators=(',', ':')))


def upload_poster_info(item_id, image_path):
    # url = 'http://localhost:8096/emby/Items/183/Images/Primary'
    f = open(image_path, 'rb')
    b6_pic = base64.b64encode(f.read())
    url = 'http://localhost:8096/emby/Items/' + str(item_id) + '/Images/Primary?api_key=e9cdf437c2c84b088c18008d6d225172'
    headers = {
        'Content-Type': 'image/jpeg'
    }

    response = requests.post(headers=headers, url=url, data=b6_pic)
    return response.text


# ----------------------------------------- 更新演员信息
def get_actor_info(actor_id: int):
    url = '{0}/emby/Users/adc41b08c4b1425a8dec3e90bdf611e7/Items/{1}'.format(domain, actor_id)
    headers = {
        'accept': 'application/json',
    }
    # 参数
    params = {
        'api_key': api_key
    }
    # 请求数据
    response = requests.get(headers=headers, url=url, params=params)

    # 查询失败
    if response.status_code != 200:
        return None

    return response.json()


# http://localhost:8096/emby/Items/107
# 更新员工信息
def update_actor_info(actor_id):
    actor_data = get_actor_info(actor_id)
    actor_data["Overview"] = "这个是修改的"
    url = '{0}/emby/Items/{1}'.format(domain, actor_id)
    headers = {
        'Accept': '*/*',
        "Content-Type": "application/json;charset=UTF-8",
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36',
    }
    # 参数
    params = {
        'api_key': api_key
    }
    # 请求数据
    response = requests.post(headers=headers, url=url, params=params, data=json.dumps(actor_data))

    # 查询失败
    if response.status_code != 200:
        return None

    return response.text


def test():
    # https://pymediainfo.readthedocs.io/en/stable/
    # pip install pymediainfo
    # https://www.cnblogs.com/nmap/p/9336707.html
    media_info = MediaInfo.parse(r"/Users/armyant/Documents/java_project/utf8-jsp/PornHub/91刘先生超火爆身材留学生，骚气十足.mp4")
    for track in media_info.tracks:
        if track.track_type == "Video":
            print("Bit rate: {t.bit_rate}, Frame rate: {t.frame_rate}, "
                  "Format: {t.format}".format(t=track)
                  )
            print("Duration (raw value):", track.duration)
            print("Duration (other values:")
            pprint(track.other_duration)
        elif track.track_type == "Audio":
            print("Track data:")
            pprint(track.to_data())


# python .\person_util.py
if __name__ == '__main__':
    # actor_id = get_actorer_id("Wu Ma")
    # print(actor_id)
    #
    # return_result = update_person_img(actor_id, r'/Users/armyant/Documents/develop/movie/阿拉丁/abc.jpg')
    # print(return_result)

    # 下载演员
    # temp_info = get_all_actorer()
    # for item in dict(temp_info)['Items']:
    #     print(item)

    # get_simple_users('Robin Williams')
    # upload_poster_info(183, r'/Users/armyant/Documents/develop/movie/阿拉丁/poster.jpg')
    # test()
    # get_actor_info("神ユキ")

    image_root_path = Path(r'E:\emby\video_actor_pic\pic')
    update_actorer_pic_all()

    # 更新av头像
    # update_actorer_pic_jav(r'E:\emby\video_actor_pic\gfriends-2.5\Content')

    # response_info = update_actor_info(3125)
    # print(response_info)
